package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService{

    @Autowired
    private RoleMapper roleMapper;

    public void saveOrUpdate(Role entity,Long[] perId,Long[] menuIds) {

        //判断是保存还是添加操作
        if (entity.getId() == null) {
            roleMapper.insert(entity);
        }else{
            //在修改操作中,要先删除旧的关系,在重新保存新的关系
            roleMapper.deleteByRelation(entity.getId());
            roleMapper.deleteByRelationOrMenu(entity.getId());
            roleMapper.updateByPrimaryKey(entity);
        }

        //添加外键关系
        if (perId != null) {
            for (Long pId : perId) {
                roleMapper.insertByRelation(entity.getId(),pId);
            }
        }
        //添加外键关系
        if (menuIds != null) {
            for (Long menuId : menuIds) {
                roleMapper.insertByRelationOrMenu(entity.getId(),menuId);
            }
        }

    }

   public void delete(Long id) {
       //要先删除角色和权限的关系,才能删除角色
       roleMapper.deleteByRelation(id);
       roleMapper.deleteByRelationOrMenu(id);
       roleMapper.deleteByPrimaryKey(id);
    }

    public Role get(Long id) {

        return roleMapper.selectByPrimaryKey(id);
    }

    public List<Role> selectList() {

        return roleMapper.selectAll();
    }

    public PageResult queryResult(QueryObject qo) {
        Integer rows = roleMapper.queryForCount(qo);
        //判断数据库中的记录数是否为null
        if (rows==0) {
            return PageResult.EMPRY_PAGE;
        }
        //===============
        //如果数据库中有数据
        List<Role> data = roleMapper.queryForPage(qo);

        return new PageResult(data,rows,qo.getCurrentPage(),qo.getPageSize());
    }
}
